from flask import render_template, jsonify, request, session

from models import db
from models.index import News, Follow, User, Category
from . import index_blu


@index_blu.route("/")
def index():
    # 查询用户是否登录
    user_id = session.get("user_id", 0)
    nick_name = session.get("nick_name", "")

    # 查询点击量最多的前6个新闻信息
    clicks_top_6_news = db.session.query(News).order_by(-News.clicks).limit(6)

    # 查询所有分类
    cats = db.session.query(Category).all()

    return render_template("index/index.html", clicks_top_6_news=clicks_top_6_news, nick_name=nick_name,cats=cats)


@index_blu.route("/newslist")
def category_news():
    # 获取前端传递过来的数据
    # / newslist?page = 1 & cid = 0 & per_page = 10
    page = request.args.get("page", 1)  # 请求的那一页数
    cid = int(request.args.get("cid", 0))  # 请求的类型
    per_page = request.args.get("per_page", 1)  # 每一页的个数

    # 数据库中查询数据
    # paginate = db.session.query(News).paginate(page=int(page), per_page=int(per_page), error_out=False
    # 如果cid是0，表示要看最新的，如果不是0则按照原来规则查询
    if cid == 0:
        paginate = db.session.query(News).order_by(-News.create_time).filter(News.status == 0).paginate(page=int(page),
                                                                                                        per_page=int(
                                                                                                            per_page),
                                                                                                        error_out=False)
    else:
        cid += 1  # 由于测试数据分类中从0开始，而数据库中是从1开始的，所以用户点击的1实际上是2
        # paginate = db.session.query(News).filter(News.category_id == cid).paginate(page=int(page), per_page=int(per_page), error_out=False)
        paginate = db.session.query(News).filter(News.category_id == cid, News.status == 0).order_by(
            -News.create_time).paginate(page=int(page), per_page=int(per_page), error_out=False)

    ret = {
        "totalPage": paginate.pages,
        "newsList": [new.to_dict() for new in paginate.items]
    }

    return jsonify(ret)


# 点击新闻请求页面
@index_blu.route("/detail/<int:news_id>")
def detail(news_id):
    # 根据news_id查询这个新闻的详情
    news = db.session.query(News).filter(News.id == news_id).first()

    # 新闻对应的作者
    news_author = news.user
    # 作者的写的文章数量
    news_author.news_num = news_author.news.count()
    # 作者的被关注数量
    followed_num = news_author.followed.count()
    # 登录的用户id
    user_id = session.get("user_id")
    # 登录的用户名
    nick_name = session.get("nick_name")

    # 记录文章作者是否被登录用户关注
    news.is_to_pay = False

    try:
        result = db.session.query(Follow).filter(Follow.follower_id == news_author.id,
                                                 Follow.followed_id == user_id).first()

        if result:
            news.is_to_pay = True

    except Exception as e:
        print(e)

    # 记录文章是否被用户收藏
    if user_id in [i.id for i in news.collected_user]:
        news.is_coll = False
    else:
        news.is_coll = True

    # 把作者的id添加到session
    session["f_user_id"] = news_author.id

    # 查询点击量最多的前6个新闻信息
    news.clicks_top_6_news = db.session.query(News).order_by(-News.clicks).limit(6)

    user = db.session.query(User).filter(User.id == user_id).first()
    if user:

        like_comment = user.like_comment

        return render_template("index/detail.html", news=news, nick_name=nick_name,
                               news_author=news_author, followed_num=followed_num, like_comment=like_comment)
    else:
        return render_template("index/detail.html", news=news, nick_name=nick_name, news_author=news_author,
                               followed_num=followed_num)


# 关于我们
@index_blu.route("/about_root")
def about_root():
    return render_template('index/about.html')


# 联系我们
@index_blu.route("/contact_root")
def contact_root():
    return render_template('index/contact.html')
